<template>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" class="elDiaLog" lock-scroll
		width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">

		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading">
			<el-form 
			ref="dataFormRef" 
			:model="formData" 
			:rules="rules" 
			label-width="130px">
			    <el-form-item required label="工程名称" prop="name">
			        <el-input v-model="formData.name" placeholder="请输入工程名称" />
			    </el-form-item>
			    <el-form-item required label="所属公司" prop="cid">
			        <el-tree-select v-model="formData.cid" 
						:data="baseConfigStore.newExCompanyList"
						check-strictly 
						:render-after-expand="false"
			            style="width: 100%" 
						placeholder="请选择所属公司"  >
					<template v-slot:default="{node, data }">
							<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
						</template>
					</el-tree-select>	
			    </el-form-item>
			    <el-form-item required label="负责人" prop="director">
			        <el-select v-model="formData.director" 
								placeholder="请选择负责人" 
								style="width: 100%">
			            <el-option v-for="(item, index) in userFList" 
							:key="item.uid" 
							:label="item.name"
			                :value="item.uid">
							<treeBlock :dataItem="item" :typeClass="2"></treeBlock>
			            </el-option>
			        </el-select>
			    </el-form-item>
			    <el-form-item required label="前期手续管理员" prop="qqsx_user">
			        <el-select v-model="formData.qqsx_user" placeholder="请选择前期手续管理员" style="width: 100%">
			            <el-option v-for="(item, index) in userFList" :key="item.uid" :label="item.name"
			                :value="item.uid">
			               <treeBlock :dataItem="item" :typeClass="2"></treeBlock>
			            </el-option>
			        </el-select>
			    </el-form-item>
			    <el-form-item required label="现场管理员" prop="xc_user">
			        <el-select v-model="formData.xc_user" placeholder="请选择现场管理员" style="width: 100%">
			            <el-option v-for="(item, index) in userFList" :key="item.uid" :label="item.name"
			                :value="item.uid">
			                <treeBlock :dataItem="item" :typeClass="2"></treeBlock>
			            </el-option>
			        </el-select>
			    </el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="['act_info'].includes(dialogStatus)" v-loading="loading">
			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1" 
					label="工程名称：">{{dataInfo.name}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="所属公司：">{{dataInfo.company?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="负责人：">
					<div class="gly">
						<div class="glyInfo">
							<img class="glyInfo_img" :src="dataInfo.directorInfo?.avatar" alt="" />
							<span class="glyInfo_txt">{{dataInfo.directorInfo?.name}}</span>
						</div>
					</div>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
					label="前期手续管理员：">
					<div class="gly">
						<div class="glyInfo">
							<img class="glyInfo_img" :src="dataInfo.qqsxInfo?.avatar" alt="" />
							<span class="glyInfo_txt">{{dataInfo.qqsxInfo?.name}}</span>
						</div>
						<el-link type="primary" @click="openDialog('act_progress',dataInfo,1)">查看进度</el-link>
					</div>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="现场管理员：">
					<div class="gly">
						<div class="glyInfo">
							<img class="glyInfo_img" :src="dataInfo.xcInfo?.avatar" alt="" />
							<span class="glyInfo_txt">{{dataInfo.xcInfo?.name}}</span>
						</div>
						<el-link type="primary" @click="openDialog('act_progress',dataInfo,2)">查看进度</el-link>
					</div>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="添加时间：">
				{{dataInfo.add_time_text}}
				</el-descriptions-item>
				
				
			</el-descriptions>	
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info'].includes(dialogStatus)"  @click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" :disabled="loading" :loading="loading" type="primary" 
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'修改':'确 定'}}</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" 
					@click="closeDialog">取 消</el-button>
			</div>
		</template>

		<engineProgressEdit v-if="dialogAdd.visible"
				v-model="dialogAdd.visible"
				:dialogTitle="dialogAdd.title"
				:dialogTableValue="dialogAdd.value"
				:dialogStatus="dialogAdd.status"
				:dialogTableType="dialogAdd.type"
				></engineProgressEdit>
				
	</el-dialog>


</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import { BUSINESS_TYPE } from "@/utils/constant";
	import engineProgressEdit from "./engineProgressEdit.vue";
	//接口地址
	import {
	    addEngineering,
	    eidtEngineering,
	    getEngineeringDetail,
	    getUserOptions
	} from "@/api/engine";
	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		}
	});
	
	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dataInfo = ref<any>({});
	const formData = ref<any>({
		id: undefined,
		name: "",//工程名称
		cid: "",//所属公司
		director: "",//负责人
		qqsx_user: "",//前期手续管理员
		xc_user: "" //请选择现场管理员
	})
	const rules = reactive<any>({
		name: [{ required: true, message: "请输入工程名称", trigger: "blur" }],
		cid: [{ required: true, message: "请选择所属公司", trigger: "blur" }],
		director: [{ required: true, message: "请选择负责人", trigger: "blur" }],
		qqsx_user: [{ required: true, message: "请选择前期手续管理员", trigger: "blur" }],
		xc_user: [{ required: true, message: "请选择现场管理员", trigger: "blur" }]
	})

	watch(
		() => props.dialogTableValue,
		() => {
			if(['act_info','act_edit'].includes(props.dialogStatus))
			{
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
				console.log('添加信息')
			}
		}, { deep: true, immediate: true })

	// users: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
	// 提交新增内容/or修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			if (valid) {
				
				let data : any = {
					id: formData.value.id,
					name: formData.value.name,//工程名称
					cid: formData.value.cid,//所属公司
					director: formData.value.director,//负责人
					qqsx_user: formData.value.qqsx_user,//前期手续管理员
					xc_user:formData.value.xc_user //请选择现场管理员
				}
				
				if (formData.value.id) {
					ElMessageBox.confirm("确定要修改信息?", "警告", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(() => {
						eidtEngineering(data).then((res) => {
							console.log(res)
							emit('initRefreshList');
							loading.value = false;
							ElMessage({ message: '修改成功', type: 'success' ,duration:1000})
							closeDialog();
						}).finally(() => {
							loading.value = false;
						})
					}).catch(() => {
						loading.value = false;
					});
				}
				else {
					loading.value = true;
					addEngineering(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading.value = false;
						ElMessage({ message: '添加成功', type: 'success' ,duration:1000})
						closeDialog();
					}).finally(() => {
						loading.value = false;
					})
				}
			}
		});
	}

	// 关闭弹窗
	function closeDialog() {
		if (!loading.value) {
			emit('update:modelValue', false)
		}
	}

	// 获取详情
	function getAuditDetail(row) {
		loading.value = true;
		getEngineeringDetail({ id: row.id }).then((res) => {
			let data = res.data;
			dataInfo.value = res.data;
			formData.value.id = res.data.id;
			formData.value.name = res.data.name;
			formData.value.cid = res.data.cid;
			formData.value.director = res.data.director;
			formData.value.qqsx_user = res.data.qqsx_user;
			formData.value.xc_user = res.data.xc_user;
		}).finally(() => {
			loading.value = false;
		})
	}



	const userFList : any = ref([]);

	//获取负责人列表
	function getUserOpti(id: any) {
	    getUserOptions({ cid: id }).then((res) => {
	        userFList.value = res.data;
	        formData.value.director = findIdInArray(formData.value.director, userFList.value);
	        formData.value.qqsx_user = findIdInArray(formData.value.qqsx_user, userFList.value);
	        formData.value.xc_user = findIdInArray(formData.value.xc_user, userFList.value);
	    }).finally(() => { })
	}
	// 监听公司数据变化
	watch(() => formData.value.cid, (newValue, oldValue) => {
	    if (newValue && newValue != oldValue && ['act_edit','act_add'].includes(props.dialogStatus)) {
	        getUserOpti(newValue);
	    }
	});
	function findIdInArray(a : any, b : any) {
		const foundItem = b.find(item => item.uid === a);
		return foundItem ? foundItem.id.toString() : "";
	}
	
	
	const dialogAdd = reactive<any>({
		title: "查看进度", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status:"act_add", //弹窗状态类型  :添加 act_add 编辑 act_edit 详情 act_info  
		value:{}   		  ,//携带整条参数 row
		type:1
	});
	// 打开新增表单内容
	function openDialog(type?:string, item ?: any,intype?:any) {
		console.log('查看进度')
		if(type == "act_progress")
		{
			dialogAdd.title = '查看进度';
			dialogAdd.status = "act_progress"
			dialogAdd.value = item;
			dialogAdd.visible = true;
			dialogAdd.type = intype
		}	
	}
	
	
	
	onMounted(() => {
		
	});
</script>

<style lang="scss" scoped>
	.gly{
		display: flex;
		justify-content: flex-start;
		align-items: center;
		align-content: center;
		.glyInfo{
			display: flex;
			align-items: center;
			align-content: center;
			margin-right: 10px;
			.glyInfo_img{
				width: 25px;
				height: 25px;
				border-radius: 4px;
				overflow: hidden;
			}
			.glyInfo_txt{
				margin-left: 10px;
			}
		}
		
	}
	
</style>